<template>
  <div>
    <el-input
      v-model="roleData.roleName"
      placeholder="请输入角色名称"
      clearable
    ></el-input>
    <el-tree
      ref="treeRef"
      :data="treeData"
      :props="{ label: (data) => data.meta.label }"
      node-key="path"
      show-checkbox
      @check="handleCheck"
    ></el-tree>
    <el-button
      v-if="rowData"
      type="success"
      size="default"
      @click="handleUpdate"
    >
      修改角色
    </el-button>
    <el-button v-else type="primary" size="default" @click="handleRoleAdd">
      录入角色
    </el-button>
  </div>
</template>

<script>
import { routes } from "@/router";
import { rolePost, rolePut } from "@/api/user";
export default {
  props: ["rowData", "rowIdx"],
  data() {
    return {
      treeData: routes[0].children,
      roleData: {
        roleName: "",
        checkedKeys: [],
        halfCheckedKeys: [],
      },
    };
  },
  watch: {
    rowData() {
      console.log("检测到了rowData的变化", this.rowData);
      if (this.rowData) {
        let { roleName, checkedKeys } = this.rowData;
        this.roleData.roleName = roleName;
        this.$refs.treeRef.setCheckedKeys(checkedKeys);
      } else {
        this.roleData.roleName = "";
        this.$refs.treeRef.setCheckedKeys([]); //重置tree勾选状态
      }
    },
  },
  methods: {
    handleLable(data, obj) {
      console.log(data.obj);
    },
    //用户勾选tree的时候，得到勾选的path
    handleCheck(_, { checkedKeys, halfCheckedKeys }) {
      this.roleData.checkedKeys = checkedKeys;
      this.roleData.halfCheckedKeys = halfCheckedKeys;
    },
    // 新增角色
    handleRoleAdd() {
      rolePost(this.roleData).then((res) => {
        console.log("post请求返回数据", res);
        this.$emit("add-role", {
          ...this.roleData,
          objectId: res.data.objectId,
        });
      });
    },
    handleUpdate() {
      let { objectId } = this.rowData;
      rolePut(objectId, this.roleData).then((res) => {
        this.$emit("edit-role", {
          idx: this.rowIdx,
          editData: {
            ...this.roleData,
            objectId,
          },
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
